﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Common.Library;
using System.Text.RegularExpressions;
using OnlineVideos.Data;
using System.Collections.ObjectModel;
using HtmlAgilityPack;
using OnlineVideos.Entities;
using Windows.Common.Data;

namespace OnlineMovies.Views
{
    public partial class UserBrowserPage : PhoneApplicationPage
    {
        AddShow addshow = new AddShow();
        string absolutepath = string.Empty;
        string description = string.Empty;
        string searchquery = string.Empty;
        string navigationuri = string.Empty;
        public List<string> NavigationHistory = new List<string>();
        public UserBrowserPage()
        {
            InitializeComponent();
            Loaded += UserBrowserPage_Loaded;
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("UserBrowserPage");
            }
            catch (Exception ex)
            {
                
              Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom event In UserBrowserPage.cs file.", ex);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
                NavigationContext.QueryString.TryGetValue("querytext", out description);
                NavigationContext.QueryString.TryGetValue("searchquery", out searchquery);
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo event In UserBrowserPage.cs file.", ex);
            }
          
        }
        void UserBrowserPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogEvent("UserBrowserPage", true);
                if (description == "Movies" || description == "Songs")
                {
                    webBrowser1.Navigate(new Uri("https://www.youtube.com/results?search_query=" + searchquery, UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    this.IsEnabled = false;
                }
                else if (description == "Audio")
                {
                    webBrowser1.Navigate(new Uri("http://www.songslover.pk/", UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    //webBrowser1.Navigate(new Uri("http://songspk.cc", UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");

                    this.IsEnabled = false;
                }
                else if (description == "Cast")
                {

                    string searc = string.Empty;
                    foreach (string ss in searchquery.Split(' '))
                    {
                        string sss = string.Empty;
                        char[] a = ss.ToCharArray();
                        a[0] = char.ToUpper(a[0]);
                        sss = new string(a);
                        if (string.IsNullOrEmpty(searc))
                        {
                            searc = sss;
                        }
                        else
                        {
                            searc = searc + "_" + sss;
                        }
                    }
                    webBrowser1.Navigate(new Uri("http://en.wikipedia.org/wiki/" + searc, UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    this.IsEnabled = false;

                }
                else if (description == "Lyrics")
                {
                    string searc = string.Empty;
                    foreach (string ss in searchquery.Split(' '))
                    {
                        string sss = string.Empty;
                        char[] a = ss.ToCharArray();
                        a[0] = char.ToUpper(a[0]);
                        sss = new string(a);
                        if (string.IsNullOrEmpty(searc))
                        {
                            searc = sss;
                        }
                        else
                        {
                            searc = searc + "_" + sss;
                        }
                    }
                    int showid = AppSettings.ShowUniqueID;
                    if (Constants.connection.Table<CategoriesByShowID>().Where(i => i.ShowID == showid && i.CatageoryID == 18).FirstOrDefaultAsync().Result != null)
                    {
                        //telugu
                        webBrowser1.Navigate(new Uri("http://www.atozsongslyrics.com/", UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    }
                    else if (Constants.connection.Table<CategoriesByShowID>().Where(i => i.ShowID == showid && i.CatageoryID == 19).FirstOrDefaultAsync().Result != null)
                    {
                        //tamil
                        webBrowser1.Navigate(new Uri("http://www.magicalsongs.net/", UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    }
                    else
                        webBrowser1.Navigate(new Uri("http://www.lyricsmint.com/", UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    //webBrowser1.Navigate(new Uri("http://www.lyrics4u.co/search/label/" + searc, UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    this.IsEnabled = false;
                }

                else
                {
                    webBrowser1.Navigate(new Uri("http://www.bing.com/search?q=" + description, UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    //webBrowser1.Navigate(new Uri("http://www.questionpapers.net.in/question_papers/physics_questions/1.html", UriKind.RelativeOrAbsolute), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                    this.IsEnabled = false;
                }
                webBrowser1.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(webBrowser1_Navigated);
                if (!string.IsNullOrEmpty(Constants.FinalUrl) && (ResourceHelper.AppName == Apps.Online_Education.ToString() || ResourceHelper.AppName == Apps.DrivingTest.ToString()))
                {
                    webBrowser1.Navigate(new Uri(Constants.FinalUrl), null, "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)");
                }
            }
            catch (Exception ex)
            {
                
             Exceptions.SaveOrSendExceptions("Exception in UserBrowserPage_Loaded event In UserBrowserPage.cs file.", ex);
            }
        }

        private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
        {

            try
            {
                List<ShowLinks> showlinks = addshow.GetShowLinks();
                if (description == "Lyrics")
                {
                    Constants.Lyrics = e.Value.ToString();
                    string lyrics = HttpUtility.HtmlDecode(Regex.Replace(Constants.Lyrics, "<[^>]+?>", ""));
                    //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                    ShowLinks links = new ShowLinks();

                    if (showlinks.Where(i => i.ShowID == AppSettings.ShowUniqueID).FirstOrDefault() != null)
                    {
                        if (showlinks.Where(i => i.ShowID == AppSettings.ShowUniqueID && i.LinkType == "Audio" && i.Title == AppSettings.LiricsLink).FirstOrDefault() != null)
                        {
                            ShowLinks lyricsList = showlinks.Where(i => i.ShowID == AppSettings.ShowUniqueID && i.LinkType == "Audio" && i.Title == AppSettings.LiricsLink).FirstOrDefault();
                            lyricsList.Description = lyrics;
                            Constants.connection.UpdateAsync(lyricsList);
                        }
                    }
                    Constants.Lyrics = string.Empty;
                    Constants.DownloadTimer.Start();
                    NavigationService.GoBack();

                }
                else
                {
                    string des = HttpUtility.HtmlDecode(Regex.Replace(e.Value.ToString(), "<[^>]+?>", ""));
                    Constants.Description.Append(" " + des.Trim()).Replace("\t", "").Replace("\n", "").Replace("\r", "");
                    WebClient wb = new WebClient();
                    wb.DownloadStringAsync(new Uri(Constants.FinalUrl, UriKind.Absolute));
                    wb.DownloadStringCompleted += wb_DownloadStringCompleted;

                }
            }
            catch (Exception ex)
            {
                
              Exceptions.SaveOrSendExceptions("Exception in webBrowser1_ScriptNotify event In UserBrowserPage.cs file.", ex);
            }
          
           
        }

        void wb_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    string pagehtml = e.Result.ToString();
                    Constants.OnlineImageUrls1 = new ObservableCollection<string>();
                    Constants.OnlineImageUrls1 = GetImages(pagehtml);
                    Constants.DownloadTimer.Start();
                    NavigationService.GoBack();
                }
            }
            catch (Exception ex)
            {
                Constants.DownloadTimer.Start();
                Exceptions.SaveOrSendExceptions("Exception in wb_DownloadStringCompleted event In UserBrowserPage.cs file.", ex);
                NavigationService.GoBack();
            }
        }
        void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                Constants.FinalUrl = e.Uri.ToString();
                if (!NavigationHistory.Contains(e.Uri.ToString()))
                    NavigationHistory.Add(e.Uri.ToString());
            }
            catch (Exception ex)
            {
                
              Exceptions.SaveOrSendExceptions("Exception in webBrowser1_Navigated event In UserBrowserPage.cs file.", ex);
            }

        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            Constants.DownloadTimer.Start();
            if (NavigationHistory.Count > 0)
            {
                e.Cancel = true;
                NavigateBack();
            }
            else
                base.OnBackKeyPress(e);
        }

        public void NavigateBack()
        {
            try
            {
                webBrowser1.InvokeScript("eval", "history.go(-1)");
                NavigationHistory.RemoveAt(NavigationHistory.Count - 1);
            }
            catch
            {
                NavigationService.GoBack();
            }
        }
        public ObservableCollection<string> GetImages(string input)
        {
            ObservableCollection<string> list = new ObservableCollection<string>();
            try
            {
            
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(input);

                foreach (HtmlNode node in doc.DocumentNode.SelectNodes(" //img"))
                {
                    if (node.OuterHtml.Contains("src") || node.OuterHtml.Contains("data-src") || node.OuterHtml.Contains("dfr-src") || node.OuterHtml.Contains("deferredsrc"))
                    {
                        if (((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["data-src"] : node.Attributes["src"]).Value.StartsWith("http"))
                        {



                            list.Add(((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["data-src"] : node.Attributes["src"]).Value);
                        }
                        else
                        {

                            list.Add(absolutepath + ((node.Attributes["src"] == null) ? (node.Attributes["data-src"] == null) ? (node.Attributes["dfr-src"] == null) ? node.Attributes["deferredsrc"] : node.Attributes["dfr-src"] : node.Attributes["data-src"] : node.Attributes["src"]).Value);
                        }
                    }
                }
               
            }
            catch (Exception ex)
            {
                
             Exceptions.SaveOrSendExceptions("Exception in GetImages event In UserBrowserPage.cs file.", ex);
            }
            return list;
        }

        private void webBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
        {
            absolutepath = e.Uri.Host.ToString() + e.Uri.AbsolutePath.ToString().Substring(0,e.Uri.AbsolutePath.ToString().LastIndexOf('/')+1);
            if (description == "Audio")
            {
                //webBrowser1.InvokeScript("eval", "function clickhandler(e){e.cancelBubble = true;var links=document.links;var i;var length=links.length;var linklist=new Array(length);for(i=0;i<length;i++){if(links[i].hasAttribute('href')){linklist[i]=links[i].getAttribute('href').toString();}}window.external.notify(linklist);}");
               //webBrowser1.InvokeScript("eval", "function clickhandler(e){e.cancelBubble = true;a = document.getElementsByTagName('a');for(var i=0; i < a.length; i++){var msg=new Array();msg = a[i].href;}window.external.notify(msg);}");
                //webBrowser1.InvokeScript("eval", "function clickhandler(e){e.cancelBubble = true;var links=document.links;var i;var length=links.length;var linklist=new Array();for(i=0;i<length;i++){if(links[i].hasAttribute('href')){linklist[i]=links[i].getAttribute('href').toString();}}window.external.notify(linklist);}");
               //webBrowser1.InvokeScript("eval", "this.Add_eventHandler=function() {for (var i = 0; i < document.all.length; i++) {document.all[i].addEventListener(\"copy\", clickhandler);}}");
               //webBrowser1.InvokeScript("Add_eventHandler");
                //webBrowser1.InvokeScript("eval", "this.getlinks_eventHandler=function(e){var links=document.links;var i;var length=links.length;window.external.notify(length);}");
                //webBrowser1.InvokeScript("eval", "document.body.addEventListener('copy',getlinks_eventHandler,true);");
                //List<Uri> ss = new List<Uri>();
                //string html = webBrowser1.SaveToString();
                ////string audiolink = Regex.Split(html, "Director")[1];
                //MatchCollection Gettbody = Regex.Matches(html, @"<a[^>]*?href\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                //foreach (Match body in Gettbody)
                //{
                //    string audiourl = body.Groups[1].Value;
                //    if (audiourl.Contains(".mp3"))
                //    {
                //        ss.Add(new Uri("http://hindisongs.audio.pk" + audiourl.Replace("/file10", "").Replace(".html", "")));
                //    }
                //}
                this.IsEnabled = true;
               
            }
            else
            {
                
                //document.selection.createRange().innerText

                try
                {
                    webBrowser1.InvokeScript("eval", "function clickhandler(e){e.cancelBubble = true;var  dataValue= document.selection.createRange().htmlText.toString();window.external.notify(dataValue);}");
                    webBrowser1.InvokeScript("eval", "this.Add_eventHandler=function() {for (var i = 0; i < document.all.length; i++) {document.all[i].addEventListener(\"copy\", clickhandler);}}");
                    webBrowser1.InvokeScript("Add_eventHandler");
                    this.IsEnabled = true;
                }
                catch (Exception ex)
                {

                    Exceptions.SaveOrSendExceptions("Exception in webBrowser1_LoadCompleted event In UserBrowserPage.cs file.", ex);
                }
               
            }
        }

        private void btnsave_Click_1(object sender, EventArgs e)
        {
            //if (description == "Audio")
            //{
            //    string html = webBrowser1.SaveToString();
            //    //string audiolink = Regex.Split(html, "Director")[1];
            //    MatchCollection Gettbody = Regex.Matches(html, @"<a[^>]*?href\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            //    foreach (Match body in Gettbody)
            //    {
            //        string audiourl = body.Groups[1].Value;
            //        if (audiourl.Contains(".mp3"))
            //        {
            //            if (!audiourl.Contains("/comments"))
            //            {
            //                //string AudiosLink = HttpUtility.HtmlDecode(Regex.Replace(audiourl, "<[^>]+?>", ""));
            //                //Constants.AudiosLinks.Add(AudiosLink.Replace("http://", ""));
            //                Constants.AudiosLinks.Add(new Uri(audiourl));
            //                //Constants.AudiosLinks.Add(new Uri("http://hindisongs.audio.pk" + audiourl.Replace("/file10", "").Replace(".html", "")));
            //            }
                        
            //        }
            //    }
            //    NavigationService.GoBack();
            //}
            //else
            //{
                AppSettings.NavigationUrl = navigationuri;
                NavigationService.GoBack();
            //}
        }

        private void webBrowser1_Navigating_1(object sender, NavigatingEventArgs e)
        {
            navigationuri = e.Uri.ToString();
        }
    }
}